﻿
/*
* 
* API中，要做三件事
* 1、判断参数
* 2、调用业务
* 3、统一返回值
* 
* 2023/4/24
* 会员控制器
*
 * 
 * **/
using AutoMapper;
using Max.PH5_2010A.Shopping.Domain;
using Max.PH5_2010A.Shopping.DTO;
using Max.PH5_2010A.Shopping.IService;
using Max.PH5_2010A.Shopping.Service;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System.ComponentModel.DataAnnotations;

namespace Max.PH5_2010A.Shopping.API.Controllers
{

    public class TestDto
    {
        public string Name { get; set; }
        public string LoginName { get; set; }


        [Required]
        public string CardNo { get; set; }
    }

    [Route("member")]
    [ApiController]
    public class MemberController : ControllerBase
    {

        IMemberService _service;

        Microsoft.AspNetCore.Hosting.IWebHostEnvironment _environment;

        [HttpPost("test")]
        public IActionResult TEST(TestDto dto)
        {
            if (!ModelState.IsValid)
            {
                return Ok("存在必填项");
            }

            //if (string.IsNullOrEmpty(dto.Name))
            //{

            //}
            //var q = from a in _service.Select()
            //select new TestDto
            //{
            //    LoginName = a.LoginName,
            //    Name = a.Name,
            //    CardNo = a.CardNo
            //};

            return Ok("添加成功");
        }


        IMemberAddressService _addressService;
        ISystemCityService _systemCityService;

        /// <summary>
        /// 构造函数注入
        /// </summary>
        /// <param name="service"></param>
        public MemberController(IMemberService service, IWebHostEnvironment environment, IMemberAddressService addressService, ISystemCityService systemCityService)
        {
            _service = service;
            _environment = environment;
            _addressService = addressService;
            _systemCityService = systemCityService;
        }

        /// <summary>
        /// 会员登录
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpPost("login")]
        public IActionResult Login(MemberLoginDto dto)
        {
            ResponseResultDto result = new();

            //参数判断
            if (string.IsNullOrEmpty(dto.Name) || string.IsNullOrEmpty(dto.Password))
            {
                result.Code = ResponseResultCode.ParamNoVailed;
                result.Message = "无效参数";
                return BadRequest(result);
            }

            //调用业务
            var data = _service.Login(dto.Name, dto.Password);
            if (!data.Item1)
            {
                result.Code = ResponseResultCode.UsernameError;
                result.Message = data.Item2;
            }
            else
            {
                result.Data = data.Item3;
            }


            //统一返回值
            return Ok(result);
        }


        /// <summary>
        /// 会员注册
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public IActionResult Register(MemberInputDto model)
        {
            ResponseResultDto dto = new();
            //判断参数
            if (string.IsNullOrEmpty(model.LoginName))
            {
                dto.Code = ResponseResultCode.ParamNoVailed;
                dto.Message = "参数无效";
                return BadRequest(dto);
            }


            //调用业务
            var data = _service.Register(model);
            if (!data.Item1)
            {
                dto.Code = ResponseResultCode.UsernameError;
                dto.Message = data.Item2;
            }

            return Ok(dto);
        }

        /// <summary>
        /// 文件上传
        /// </summary>
        /// <param name="files"></param>
        /// <returns></returns>
        [HttpPost("upload")]
        public async Task<IActionResult> Upload()
        {
            //IFormFileCollection files
            var files = Request.Form.Files;

            ResponseResultDto dto = new();
            var path = $"{ _environment.WebRootPath }/{ System.DateTime.Now.ToString("yyyyMMdd")}";
            var result = await Common.FileUploadHelper.Upload(files, path);

            if (!result.Item1)
            {
                dto.Code = ResponseResultCode.Failed;
                dto.Message = result.Item2;
                return BadRequest(dto);
            }

            dto.Data = result.Item3;

            return Ok(dto);
        }


        #region 2023/5/8 会员地址

        /// <summary>
        /// 获取会员的地址列表
        /// </summary>
        /// <returns></returns>
        [HttpGet("address")]
        public IActionResult GetAddress(string memberId)
        {
            ResponseResultDto result = new();

            if (string.IsNullOrEmpty(memberId))
            {
                result.Code = ResponseResultCode.ParamNoVailed;
                result.Message = "无效参数";
                return Ok(result);
            }

            //获取这个前台登录的会员的收件人地址列表
            var data = _addressService.Select().Where(x => x.MemberId.ToString().Equals(memberId)).OrderByDescending(x => x.IsDefaultAddress);
            result.Data = data;
            return Ok(result);
        }

        /// <summary>
        /// 收件人地址添加
        /// </summary>
        /// <returns></returns>
        [HttpPost("address")]
        public IActionResult PostAddress(MemberAddressModel model)
        {
            ResponseResultDto result = new();

            if (string.IsNullOrEmpty(model.Name) || string.IsNullOrEmpty(model.Phone) || string.IsNullOrEmpty(model.Address))
            {
                result.Code = ResponseResultCode.ParamNoVailed;
                result.Message = "无效参数";
                return Ok(result);
            }

            //在添加新地址时，如果这个新地址是设置为默认地址的时候，需要把数据库中原来的默认地址，设置为非默认地址
            if (model.IsDefaultAddress)
            {
                var d = _addressService.Select().Where(x => x.MemberId == model.MemberId).ToList();
                d.ForEach(x =>
                {
                    x.IsDefaultAddress = false;
                    _addressService.Update(x);
                });
            }

            int row = _addressService.Insert(model);
            if (row <= 0)
            {
                result.Code = ResponseResultCode.Failed;
                result.Message = "操作失败";
                return Ok(result);
            }

            return Ok(result);
        }


        /// <summary>
        /// 获取城市列表
        /// </summary>
        /// <returns></returns>
        [HttpGet("city")]
        public IActionResult GetSystemCityList()
        {
            ResponseResultDto dto = new();
            var data = _systemCityService.GetRecursionCity();
            dto.Data = data;
            return Ok(dto);

        }

        #endregion
    }
}
